const express = require('express')
const router = express.Router()
const auth = require('../middleware/auth')
const productService = require('../services/productService')
const logger = require('../utils/logger')

/**
 * 获取商品列表
 * GET /api/products
 */
router.get('/', async (req, res) => {
  try {
    const {
      category,
      type,
      status,
      isHot,
      isNew,
      search,
      page,
      limit,
      sortBy,
      sortOrder
    } = req.query

    const options = {
      category,
      type,
      status: status ? parseInt(status) : undefined,
      isHot: isHot ? isHot === 'true' : undefined,
      isNew: isNew ? isNew === 'true' : undefined,
      search,
      page: page ? parseInt(page) : undefined,
      limit: limit ? parseInt(limit) : undefined,
      sortBy,
      sortOrder
    }

    const result = await productService.getProducts(options)

    res.json({
      success: true,
      code: 200,
      message: '获取商品列表成功',
      data: result
    })
  } catch (error) {
    logger.error('获取商品列表失败:', error)
    res.status(400).json({
      success: false,
      code: 400,
      message: error.message || '获取商品列表失败'
    })
  }
})

/**
 * 获取商品分类
 * GET /api/products/categories
 */
router.get('/categories', async (req, res) => {
  try {
    const categories = await productService.getCategories()

    res.json({
      success: true,
      code: 200,
      message: '获取商品分类成功',
      data: categories
    })
  } catch (error) {
    logger.error('获取商品分类失败:', error)
    res.status(400).json({
      success: false,
      code: 400,
      message: error.message || '获取商品分类失败'
    })
  }
})

/**
 * 获取热门商品（简化路径）
 * GET /api/products/hot
 */
router.get('/hot', async (req, res) => {
  try {
    const limit = req.query.limit ? parseInt(req.query.limit) : 10
    const products = await productService.getHotProducts(limit)

    res.json({
      success: true,
      code: 200,
      message: '获取热门商品成功',
      data: products
    })
  } catch (error) {
    logger.error('获取热门商品失败:', error)
    res.status(400).json({
      success: false,
      code: 400,
      message: error.message || '获取热门商品失败'
    })
  }
})

/**
 * 获取商品详情
 * GET /api/products/:id
 */
router.get('/:id', async (req, res) => {
  try {
    const productId = parseInt(req.params.id)
    if (!productId) {
      return res.status(400).json({
        success: false,
        code: 400,
        message: '商品ID无效'
      })
    }

    const product = await productService.getProductById(productId)

    res.json({
      success: true,
      code: 200,
      message: '获取商品详情成功',
      data: product
    })
  } catch (error) {
    logger.error('获取商品详情失败:', error)
    res.status(400).json({
      success: false,
      code: 400,
      message: error.message || '获取商品详情失败'
    })
  }
})

/**
 * 获取热门商品
 * GET /api/products/hot/list
 */
router.get('/hot/list', async (req, res) => {
  try {
    const limit = req.query.limit ? parseInt(req.query.limit) : 10
    const products = await productService.getHotProducts(limit)

    res.json({
      success: true,
      code: 200,
      message: '获取热门商品成功',
      data: products
    })
  } catch (error) {
    logger.error('获取热门商品失败:', error)
    res.status(400).json({
      success: false,
      code: 400,
      message: error.message || '获取热门商品失败'
    })
  }
})

/**
 * 获取新品商品
 * GET /api/products/new/list
 */
router.get('/new/list', async (req, res) => {
  try {
    const limit = req.query.limit ? parseInt(req.query.limit) : 10
    const products = await productService.getNewProducts(limit)

    res.json({
      success: true,
      code: 200,
      message: '获取新品商品成功',
      data: products
    })
  } catch (error) {
    logger.error('获取新品商品失败:', error)
    res.status(400).json({
      success: false,
      code: 400,
      message: error.message || '获取新品商品失败'
    })
  }
})

/**
 * 检查商品库存
 * GET /api/products/:id/stock
 */
router.get('/:id/stock', async (req, res) => {
  try {
    const productId = parseInt(req.params.id)
    const quantity = parseInt(req.query.quantity) || 1

    if (!productId) {
      return res.status(400).json({
        success: false,
        code: 400,
        message: '商品ID无效'
      })
    }

    const hasStock = await productService.checkStock(productId, quantity)

    res.json({
      success: true,
      code: 200,
      message: '检查库存成功',
      data: {
        hasStock,
        productId,
        quantity
      }
    })
  } catch (error) {
    logger.error('检查商品库存失败:', error)
    res.status(400).json({
      success: false,
      code: 400,
      message: error.message || '检查商品库存失败'
    })
  }
})

module.exports = router